package config

import (
	"app.com/common.v1/tool"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"log"
	"os"
)

var AppConf = InitConfig()

type Config struct {
	viper      *viper.Viper
	ServerConf *ServerConfig
	RedisConf  *redis.Options
}

func InitConfig() *Config {
	conf := &Config{viper: viper.New()}
	workDir, _ := os.Getwd()
	conf.viper.SetConfigName("app")
	conf.viper.SetConfigType("yml")
	conf.viper.AddConfigPath(workDir + "/config")

	err := conf.viper.ReadInConfig()
	if err != nil {
		log.Fatalln(err)
		return nil
	}

	//server配置
	conf.readServerConfig()
	conf.initZapLog()
	conf.redisConfig()

	return conf
}

type ServerConfig struct {
	Name string
	Addr string
}

func (c *Config) readServerConfig() {
	sc := &ServerConfig{}
	sc.Name = c.viper.GetString("server.name")
	sc.Addr = c.viper.GetString("server.addr")
	c.ServerConf = sc
}

func (c *Config) initZapLog() {
	workDir, _ := os.Getwd()
	lc := &tool.LogConfig{
		DebugFileName: workDir + c.viper.GetString("zap.debugFileName"),
		InfoFileName:  workDir + c.viper.GetString("zap.infoFileName"),
		ErrorFileName: workDir + c.viper.GetString("zap.errorFileName"),
		MaxSize:       c.viper.GetInt("zap.maxSize"),
		MaxAge:        c.viper.GetInt("zap.maxAge"),
		MaxBackups:    c.viper.GetInt("zap.maxBackups"),
	}

	err := tool.InitLogger(lc)
	if err != nil {
		return
	}
}

func (c *Config) redisConfig() {
	c.RedisConf = &redis.Options{
		Addr:     c.viper.GetString("redis.host") + ":" + c.viper.GetString("redis.port"),
		Password: c.viper.GetString("redis.password"),
		DB:       c.viper.GetInt("redis.db"),
	}
}
